import { AxiosError } from 'axios';

/**
 * 用于拦截重复提交请求
 *
 * @param {Object} http
 */
export function setupRepeatSubmitInterceptor(http) {
  const requests = new Map();
  function interceptor(config) {
    const { method, url } = config;
    const key = [method, url].join(':');
    if (requests.has(key)) {
      const code = 'ERR_REPEAT_SUBMIT';
      const message = 'Repeat request submission.';
      const error = new AxiosError(message, code, config);
      return Promise.reject(error);
    }
    requests.set(key, config);
    return config;
  }

  function complete(config) {
    const { method, url } = config;
    const key = [method, url].join(':');
    requests.delete(key);
  }

  http.interceptors.request.use(interceptor, function (error) {
    return Promise.reject(error);
  });

  http.interceptors.response.use(
    function (res) {
      res.config && complete(res.config);
      return res;
    },
    function (error) {
      error.config && complete(error.config);
      return Promise.reject(error);
    }
  );
}
